#encoding=utf8

import MySQLdb

class MyTran():
    def __init__(self, con):
        self.con = con

    def __enter__(self):
        self.cursor = con.cursor()
        return self

    def __call__(self, *args, **kargs):
        sql = args[0]
        params = kargs
        count = self.cursor.execute(sql, params)
        self.con.commit()

    def __getattr__(self, name):
        if name == 'results':
            return self.cursor.fetchall()
        elif name == 'result':
            return self.cursor.fetchone()
        else:
            return None

    def __exit__(self, type, value, tb):
        if value:
            self.con.rollback()
        self.cursor.close()
        self.con.close()
        

con = MySQLdb.connect(host='localhost',user='root',db='test',port=3306)
with MyTran(con) as db:
    db('select * from entries')
    for r in db.results:
        print r[1]
    db("""INSERT INTO test.entries(id, title, content, posted_on)
        VALUES(0, %(title)s, %(content)s, %(postedOn)s);""",
        title='my article', content='I am a good boy', postedOn='2015-11-12')
    db('select * from entries')
    for r in db.results:
        print r[0],r[1]
